package com.sxj.web.servlet;

import com.sxj.web.entity.Emp;
import com.sxj.web.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author 石小俊
 * @date 2024年03月01日 19:46
 */
@WebServlet("*.emp")
public class EmpServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        System.out.println("****************我进来了****************");
        // 获取Servlet访问命令
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        String path = request.getServletPath();
        System.out.println("path:" + path);
        switch (path) {
            case "/add.emp":
                addEmp(request, response);
                break;
            case "/findAll.emp":
                findAll(request, response);
                break;
            case "/findById.emp":
                findById(request, response);
                break;
            case "/modify.emp":
                modifyEmp(request, response);
                break;
            case "/delete.emp":
                deleteEmp(request, response);
                break;
            default:
                out.print("<h1 style='color:red;'>您输入的请求有误,请重新输入</h1>");

        }
    }

    public void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        System.out.println("name:" + name + ",salary:" + salary + ",gender:" + gender + ",edu:" + edu + ",hobbies:" + Arrays.toString(hobbies));

        Connection conn = null;
        PreparedStatement ps = null;
        String url = "jdbc:mysql://127.0.0.1:3306/ems?useUnicode=true&characterEncoding=utf-8";
        try {
            // JDBC操作
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append("insert into ")
                    .append(" t_emp ")
                    .append("   (name,salary,gender,edu,hobbies)")
                    .append(" values ")
                    .append("   (?,?,?,?,?)")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            // 执行sql
            ps.executeUpdate();
            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath + "/findAll.emp");

        } catch (Exception e) {
            e.printStackTrace();
            out.print("<h1 style='color:red;'>对不起,添加失败,错误原因:" + e.getMessage() + "</h1>");
        }
    }

    public void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 此处查询数据库中的数据,页面部分在JSP中
        // 因此,当数据查询结束之后跳转到JSP显示
        // 使用JDBC查询数据库中的数据,将其展现到页面中
        // 由于数据与页面是分离开来的,因此后台查询时获取到的数据,最终需要通过一定的方式传递到JSP页面中
        String url = "jdbc:mysql://127.0.0.1:3306/ems?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Emp> emps = new ArrayList<>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" select id,name,salary ")
                    .append(" from t_emp ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            // 每遍历一行数据,生成一个对象
            while (rs.next()) {
                Emp emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                // 每生成一个对象,都将其添加到对应的对象集合中
                emps.add(emp);
            }

            // 到此时,对象集合数据全部获取到了
            // 如何将其传递到JSP中?
            // 在JSP中,提供了四大作用域功能,此时先使用request
            // 将数据value存储到request中
            request.setAttribute("emps", emps);
            // 根据key从request中取出对应的value
            // 如果数据存储在request中,获取数据者需要与存储者共享request
//            request.getAttribute("key");
            // 因此,想要在JSP中获取此时存储的数据,则跳转的JSP页面与当前Servlet必须共享请求
            request.getRequestDispatcher("/ems/empList.jsp").forward(request, response);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void findById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        System.out.println("id:" + id);
        // 进入修改页面之后,需要设置默认值
        // 其值是根据主键查询得到的
        String url = "jdbc:mysql://127.0.0.1:3306/ems?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Emp emp = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" select id,name,salary,gender,edu,hobbies ")
                    .append(" from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                emp = new Emp();
                emp.setId(rs.getInt("id"));
                emp.setName(rs.getString("name"));
                emp.setSalary(rs.getDouble("salary"));
                emp.setGender(rs.getString("gender"));
                emp.setEdu(rs.getString("edu"));
                emp.setHob(rs.getString("hobbies"));
            }
            request.setAttribute("emp",emp);
            request.getRequestDispatcher("/ems/modifyEmp.jsp").forward(request,response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void modifyEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String gender = request.getParameter("gender");
        String edu = request.getParameter("edu");
        String[] hobbies = request.getParameterValues("hobbies");
        System.out.println("name:" + name + ",salary:" + salary + ",gender:" + gender + ",edu:" + edu + ",hobbies:" + Arrays.toString(hobbies));

        String url = "jdbc:mysql://127.0.0.1:3306/ems?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" update t_emp ")
                    .append(" set ")
                    .append("   name = ?, ")
                    .append("   salary = ?, ")
                    .append("   gender = ?, ")
                    .append("   edu = ?, ")
                    .append("   hobbies = ? ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setDouble(2, Double.parseDouble(salary));
            ps.setString(3, gender);
            ps.setString(4, edu);
            ps.setString(5, StringUtil.arrayToString(hobbies));
            ps.setInt(6, Integer.parseInt(id));
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void deleteEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String url = "jdbc:mysql://127.0.0.1:3306/ems?useUnicode=true&characterEncoding=utf-8";
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "root", "");
            String sql = new StringBuffer()
                    .append(" delete from t_emp ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1,Integer.parseInt(id));
            ps.executeUpdate();
            response.sendRedirect(request.getContextPath()+"/findAll.emp");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
